package com.presto.directo.mvvm.view

import android.content.Context
import android.os.Bundle
import android.util.SparseArray
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.Target
import com.presto.directo.R
import com.presto.directo.base.BaseActivity
import com.presto.directo.databinding.ActivityRepayBinding
import com.presto.directo.entity.*
import com.presto.directo.net.*
import com.presto.directo.utils.*
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.*
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView

class RepayActivity : BaseActivity() {

    private var remainAmount = ""
    private val repayInfoArray = SparseArray<RepayInfoEntity>()
    private val binding by lazy { ActivityRepayBinding.inflate(layoutInflater) }
    private val start = 1
    private var busiId = ""
    private var extensionEntity: ExtensionEntity? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Af.show_repay_page.track(this)
        binding.tvCompany.text = "BENEFICIARIO:" + getString(R.string.app_name)
        extensionEntity = intent.getSerializableExtra("extension") as ExtensionEntity?
        remainAmount = intent.getStringExtra("amount") ?: ""
        busiId = intent.getStringExtra("busiId") ?: ""
        if (extensionEntity == null) {
            binding.tvRemainAmount.text = remainAmount.appendAmountUnit()
        } else {
            binding.tvRemainAmount.text = extensionEntity!!.remain_amount.appendAmountUnit()
            binding.llRate.isVisible = !extensionEntity?.fee_rate.isNullOrBlank()
            binding.llAmount.isVisible = !extensionEntity?.fee.isNullOrBlank()
            binding.tvExtensionRate.text = extensionEntity?.fee_rate
            binding.tvExtensionAmount.text = extensionEntity?.fee.appendAmountUnit()
        }
        val titles = arrayListOf("OXXO", "Otras Tiendas")
        val commonNavigator = CommonNavigator(this)
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return titles.size
            }

            override fun getTitleView(context: Context?, index: Int): IPagerTitleView {
                val colorTransitionPagerTitleView = ColorTransitionPagerTitleView(context)
                colorTransitionPagerTitleView.normalColor = ContextCompat.getColor(this@RepayActivity, R.color.tv_color_9b)
                colorTransitionPagerTitleView.selectedColor = ContextCompat.getColor(this@RepayActivity, R.color.color_333333)
                colorTransitionPagerTitleView.text = titles[index]
                colorTransitionPagerTitleView.setOnClickListener {
                    binding.indicator.onPageScrolled(index, 0f, 0)
                    getRepayInfo(index + start)
                }
                return colorTransitionPagerTitleView
            }

            override fun getIndicator(context: Context?): IPagerIndicator {
                val linePagerIndicator = LinePagerIndicator(context)
                linePagerIndicator.mode = LinePagerIndicator.MODE_WRAP_CONTENT
                linePagerIndicator.setColors(ContextCompat.getColor(this@RepayActivity, R.color.color_accent))
                return linePagerIndicator
            }
        }
        binding.indicator.navigator = commonNavigator
        getRepayInfo(start)
    }

    override val rootView: View
        get() = binding.root

    private fun show(info: RepayInfoEntity) {
        if (extensionEntity == null) {
            binding.tvDeadline.text = info.deadline
        } else {
            binding.tvDeadline.text = extensionEntity!!.deadline_extension
        }
        binding.tvName.text = info.realName
        binding.tvCode.text = info.stpNumber
        info.second?.let {
            binding.cvQrCode.isVisible = true
            binding.tvChannel.text = it.channel
            binding.tvCodeAmount.text = it.amount.appendAmountUnit()
            if (it.payment_url.isNotEmpty()) {
                Glide.with(this)
                    .load(it.payment_url)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .into(binding.ivQrCode)
            }
            binding.tvRepayCode.text = "Referencia:" + it.paycode
            binding.tvCodeDeadline.text = "Fecha de caducidad:" + it.code_deadline
        } ?: let {
            binding.cvQrCode.isVisible = false
        }
    }

    private fun getRepayInfo(tab: Int) {
        repayInfoArray[tab]?.let {
            show(it)
        } ?: start(onNext = {
            showProgress()
            val map = getHttpMap()
            map["tab"] = tab
            map["amount"] = if (extensionEntity == null) remainAmount else extensionEntity!!.fee
            map["busi_id"] = busiId
            map["va_extension"] = if (extensionEntity == null) "0" else "1"
            val repayInfoEntity = getApiService().repay(map.sign(33)).getResult()
            repayInfoArray.put(tab, repayInfoEntity)
            show(repayInfoEntity)
        }, onComplete = {
            dismissProgress()
        })
    }

}